<?php

/**
 * 导入异常类 
 */
include(dirname(__FILE__). '/../Exception/JsonException.class.php');
include(__DIR__ . '/verify.php');

set_exception_handler('exceptionHandler');  //设置异常拦截函数，改写ThinkPHP中默认的异常处理方法

/**
 * exceptionHandler 
 * 异常拦截函数
 */
function exceptionHandler($e) {
    if($e instanceof JsonException) {
        showJson(array('s' => false, 'm' => $e->getMessage()));
    } else {
        halt2($e->__toString());
    }
}

/**
 * D2
 * D()加强版，如果不指定$model参数，则自动实例化与CONTROLLER_NAME同名的模型
 *
 * @param mixed $model
 * @access public
 * @return void
 */
function D2($model = null) {
    $model = empty($model) ? CONTROLLER_NAME : $model;

    return D($model);
}


/**
 * 错误输出
 * @param mixed $error 错误
 * @return void
 */
function halt2($error) {
    $e = array();

    /*
     * 条件中加入0是为关闭对调试模式的判断
     * 不将APP_DEBUG直接设置为false，是因为关闭调整模式后会产生各种文件缓存，如果改动配置或模板后需要清除缓存，这样很麻烦
     * 在服务器上开启PHP代码缓存后完全可以不使用ThinkPHP的缓存
     */
    if(0 && APP_DEBUG) {
        //调试模式下输出错误信息
        if(!is_array($error)) {
            $trace        = debug_backtrace();
            $e['message'] = $error;
            $e['file']    = $trace[0]['file'];
            $e['line']    = $trace[0]['line'];

            ob_start();
            debug_print_backtrace();

            $e['trace'] = ob_get_clean();
        } else {
            $e = $error;
        }
    } else {
        //否则定向到错误页面
        $error_page = C('ERROR_PAGE');

        if(!empty($error_page)) {
            redirect($error_page);
        } else {
            if(C('SHOW_ERROR_MSG')) {
                $e['message'] = is_array($error) ? $error['message'] : $error;
            } else {
                $e['message'] = C('ERROR_MESSAGE');
            }
        }
    }

    // 包含异常页面模板
    include C('TMPL_EXCEPTION_FILE');
    exit;
}


/**
 * copyDir
 * 复制目录
 *
 * @param mixed $source
 * @param mixed $destination
 * @return void
 */
function copyDir($source, $destination) {
    $result = true;

    if(!is_dir($source)) {
        throw new Exception('源目标必须是目录');
    }

    if(!is_dir($destination)) {
        if(!mkdir($destination)) {
            throw new Exception('无法创建目录');
        }
    }

    $handle = opendir($source);

    while(($file = readdir($handle)) !== false) {
        if(in_array($file, array('.', '..'))) {
            continue;
        }

        $src = $source . DIRECTORY_SEPARATOR . $file;
        $dtn = $destination . DIRECTORY_SEPARATOR . $file;

        if(is_dir($src)) {
            copyDir($src, $dtn);
        } else {
            if(!copy($src, $dtn)) {
                $result = false;
                break;
            }
        }
    }

    closedir($handle);

    return $result;
}

/**
 * removeDir
 * 删除目录
 *
 * @param mixed $dirName
 * @return void
 */
function removeDir($dirName) {
    $result = false;

    if(!is_dir($dirName)) {
        throw new Exception('只能删除目录');
    }

    $handle = opendir($dirName);

    while(($file = readdir($handle)) !== false) {
        if($file != '.' && $file != '..') {
            $dir = $dirName . DIRECTORY_SEPARATOR . $file;
            is_dir($dir) ? removeDir($dir) : unlink($dir);
        }
    }

    closedir($handle);

    $result = rmdir($dirName) ? true : false;

    return $result;
}

/**
 * mkdir2
 * 逐级创建每级目录
 *
 * @param mixed $dir
 * @return void
 */
function mkdir2($dir) {
    $tmp = explode('/', $dir);

    if(empty($tmp)) {
        return false;
    }

    $tmpPath = '';

    foreach($tmp as $v) {
        $tmpPath .= empty($v) ? '/' : '/'. $v;

        if(!is_dir($tmpPath)) {
            if(!mkdir($tmpPath)) {
                return false;
            }
        }
    }

    return true;
}

/**
 * getProfit
 * 返回盈利
 *
 * @param mixed $aderPay
 * @param mixed $siterIncome
 * @return void
 */
function getProfit($aderPay, $siterIncome) {
    return bcsub($aderPay, $siterIncome, C('money_scale'));
}

/**
 * getCtr
 * 返回结算比例，或其他需要计算比例的都可以使用此函数
 *
 * @param mixed $view
 * @param mixed $num
 * @return void
 */
function getCtr($view, $num) {
    if($view == 0 || $num == 0) {
        return '0.00';
    }

    return round($num / $view * 100, 2);
}

/**
 * getJsonInput
 * 返回rest方式提交的json数据
 *
 * @return void
 */
function getJsonInput() {
    return json_decode(file_get_contents('php://input'), true);
}

/**
 * getTotalMoney
 * 返加站长总余额
 *
 * @param mixed $daymoney
 * @param mixed $weekmoney
 * @param mixed $monthmoney
 * @return void
 */
function getTotalMoney($daymoney, $weekmoney = 0, $monthmoney = 0) {
    $daymoney   = (float)$daymoney;
    $weekmoney  = (float)$weekmoney;
    $monthmoney = (float)$monthmoney;
    $a          = bcadd($daymoney, $weekmoney, C('money_scale')); //todo:money_scale 换成常量定义的方式

    return bcadd($a, $monthmoney, C('money_scale'));
}

/**
 * getUserStatus
 * 返回会员状态
 *
 * @param mixed $s
 * @return void
 */
function getUserStatus($s) {
    $conf = C('USER_STATUS');

    return array_key_exists($s, $conf) ? $conf[$s] : '';
}

function getUserStatusCn($s) {
    return getUserStatus($s);
}


/**
 * getUserNameByUid
 * 返回会员名称
 *
 * @param mixed $uid
 * @return void
 */
function getUserNameByUid($uid) {
    $uid = (int)$uid;
    $m = D2('User');

    if(!$r = $m->getByUid($uid)) {
        return false;
    }

    return $r['user_name'];
}

/**
 * getServiceNameByUid
 * 返回客服名称
 *
 * @param mixed $uid
 * @return void
 */
function getServiceNameByUid($uid) {
    $uid = (int)$uid;
    $m   = new Common\Model\UserModel;

    if(!$r = $m->getById($uid)) {
        return false;
    }

    return $r['contact'];
}

/**
 * showJson
 * 把数据转换成json格式输出
 * 此函数会中止程序执行
 *
 * @param mixed $a
 * @return void
 */
function showJson($a) {
    echo json_encode($a);
    exit();
}

/**
 * getPlanNameByDay
 * 获取指定日期有统计信息的计划名称
 *
 * @return void
 */
function getPlanNameByDay($day = null) {
    $day = empty($day)     ? date('Y-m-d') : $day;
    $day = strtotime($day) ? $day          : date('Y-m-d');

    $m = D('PlanStats');

    if(!$r = $m->field('plan_id, plan_name')->where(['day' => $day])->order('plan_id DESC')->select()) {
        return false;
    }

    return $r;
}

/**
 * getPlanNameById
 * 根据计划编号返回计划名称
 *
 * @param mixed $id
 * @return void
 */
function getPlanNameById($id) {
    if (!$r = D('Plan')->where(['id' => $id])->getField('name')) {
        return false;
    }

    return $r;
}

/**
 * getPlanListByType
 * 根据计划类型返回计划列表
 *
 * @param mixed $type
 * @return void
 */
function getPlanListByType($type) {
    $m    = D2('Plan');
    $expr = array('type' => strtolower($type));

    return $m->where($expr)->order('status')->select();
}

/**
 * getAdById
 * 获取广告信息
 *
 * @param mixed $id
 * @return void
 */
function getAdById($id) {
    return D2('Ad')->getByAdId($id);
}

/**
 * getClickViewTime
 * 返回点显时长
 *
 * @param mixed $clickTime
 * @param mixed $viewTime
 * @return void
 */
function getClickViewTime($clickTime, $viewTime) {
    $a = strtotime($clickTime);
    $b = strtotime($viewTime);

    return $a - $b;
}

/**
 * getTrackCount
 * 返回轨迹数量
 *
 * @param mixed $track
 * @return void
 */
function getTrackCount($track) {
    if(empty($track)) {
        return 0;
    }

    return count(explode(',', $track));
}

/**
 * getClearingCn
 * 返回结算方式的中文名称
 *
 * @param mixed $clearing
 * @return void
 */
function getClearingCn($clearing) {
    $clearing  = strtolower(trim($clearing));

    if(empty($clearing)) {
        return $defaultCn;
    }

    $conf      = C('CLEARING_TYPES');
    $defaultCn = '未知';

    return array_key_exists($clearing, $conf) ? $conf[$clearing] : $defaultCn;
}

/**
 * filterClearing
 * 过滤结算周期，返回正确的结算周期
 *
 * @param mixed $s  结算周期编号，可以是单值，也可以是数组
 * @access public
 * @return void
 */
function filterClearing($s) {
    $conf = C('CLEARING_TYPE');

    if (!is_array($s)) {
        $s = [$s];
    }

    $r = [];

    foreach ($s as $v) {
        $v = (int)$v;

        if (!array_key_exists($v, $conf)) {
            continue;
        }

        $r[] = $v;
    }

    return $r;
}

/**
 * getPlanStatusCn
 * 返回计划状态中文名称
 *
 * @param mixed $s
 * @return void
 */
function getPlanStatusCn($s) {
    $s        = (int)$s;
    $conf     = C('PLAN_STATUS');
    $defaulCn = '未知';

    return array_key_exists($s, $conf) ? $conf[$s] : $defaulCn;
}

/**
 * getSiteTypeByPid
 * 返回与pid对应的站点类型
 *
 * @param int $pid
 * @return void
 */
function getSiteTypeByPid($pid = 0) {
    $m = D2('SiteType');

    return $m->getByPid($pid);
}

/**
 * getSiteTypeCnById
 * 返回站点类型中文名称
 *
 * $id其值可为单值，也可为postgresql的数组格式
 *
 * 返回值数组
 *
 * @param mixed $id
 * @return void
 */
function getSiteTypeCnById($id) {
    if(is_numeric(strpos($id, '{'))) {
        $tmp = trim($id, '{}');
        $id  = explode(',', $tmp);
    } else {
        $id = (int)$id;
    }

    $m    = D2('SiteType');
    $r    = array();
    $expr = is_array($id) ? array('s_t_id' => array('IN', $id)) : $id;

    if(!$record = $m->where($expr)->select()) {
        return false;
    }

    foreach($record as $v) {
        $r[] = $v['s_t_name'];
    }

    return $r;
}

/**
 * getImplodeSiteTypeCnById
 * 返回合并后的站点类型字符串
 *
 * @param mixed $id
 * @return void
 */
function getImplodeSiteTypeCnById($id) {
    if(!$r = getSiteTypeCnById($id)) {
        return false;
    }

    return implode(',', $r);
}

/**
 * getPrice2
 * 获取每1000次的单价
 *
 * @param mixed $preice
 * @return void
 */
function getPrice2($price) {
    if (empty($price)) {
        return false;
    }

    return $price * 1000;
}

/**
 * getPrice
 * 将1000次的单价转换成每次的单价
 *
 * @param mixed $price2
 * @return void
 */
function getPrice($price2) {
    return bcdiv($price2, 1000, C('money_scale'));
}

/**
 * getPriceForSiterByPlanId
 * 返回针对站长的单价
 *
 * @param mixed $id
 * @return void
 */
function getPriceForSiterByPlanId($id) {
    $id   = (int)$id;
    $expr = array('plan_id' => $id);

    if(!$record = D2('PlanDevice')->where($expr)->find()) {
        return false;
    }

    return $record['pd_price_3'];
}

function getPriceForAderByPlanId($planId) {
    $planId = (int)$planId;

    if (empty($planId)) {
        return false;
    }

    $expr = array('plan_id' => $planId);

    if (!$record = D2('PlanDevice')->where($expr)->find()) {
        return false;
    }

    return $record['pd_price_1'];
}

/**
 * getAdTypeCn
 * 返回广告类型中文名称
 *
 * @param mixed $t
 * @return void
 */
function getAdTypeCn($t) {
    $conf      = C('AD_TYPES');
    $defaultCn = '未知';
    $t         = strtolower($t);

    return array_key_exists($t, $conf) ? $conf[$t] : $defaultCn;
}

/**
 * getAdTypeCnByAdId
 * 返回与$id对应的广告类型中文名称
 *
 * @param mixed $id
 * @return void
 */
function getAdTypeCnByAdId($id) {
    $id   = (int)$id;
    $type = 0;

    if($ad = getAdById($id)) {
        $type = $ad['type'];
    }

    return getAdTypeCn($type);
}

/**
 * getAdStatusCn
 * 返回广告状态中文名称
 *
 * @param mixed $s
 * @return void
 */
function getAdStatusCn($s) {
    $conf      = C('AD_STATUS');
    $s         = (int)$s;
    $defaultCn = '未知';

    return array_key_exists($s, $conf) ? $conf[$s] : $defaultCn;
}

/**
 * getIncludeAdType
 * 根据计费模式返回包含的广告类型
 *
 * @param mixed $costType
 * @return void
 */
function getIncludeAdType($costType) {
    $conf     = C('COST_TYPE_INCLUDE_AD_TYPE');
    $costType = strtolower($costType);

    if(!array_key_exists($costType, $conf)) {
        return false;
    }

    $includeAdType = $conf[$costType];
    $adTypeConf    = C('AD_TYPE');
    $r             = array();

    foreach($includeAdType as $v) {
        $r[$v] = $adTypeConf[$v];
    }

    return $r;
}

/**
 * getDomainBySiteId
 * 获取网站编号对应的所有域名
 *
 * @param mixed $id
 * @return void
 */
function getDomainBySiteId($siteId, $domain = null, $status = null) {
    $siteId = (int)$siteId;
    $m      = D2('SiteDomain');

    $expr = array('site_id' => $siteId);

    if(!empty($domain)) {
        $expr['s_d_domain'] = array('EXP', "LIKE '%{$domain}%'");
    }

    if(!is_null($status) && strlen($status)) {
        $expr['s_d_status'] = $status;
    }

    return $m->where($expr)->order('s_d_id DESC')->select();
}

/**
 * get_location_ip2
 * 返回IP对应的物理地址
 *
 * @param mixed $ip
 * @return void
 */
function get_location_ip2($ip) {
    $ipFile = __DIR__ . '/qqwry.dat';
    $ipLocation = new \Org\Net\IpLocation($ipFile);
    $r = $ipLocation->getlocation($ip);

    if($r['country'] == '未知') {
        return '未知';
    }

    mb_convert_variables('utf-8', 'gbk', $r);

    return $r['country'] . $r['area'];
}

function get_location_ip($ip) {
    include_once __DIR__ . '/IpSearch.php';

    $ipFile = __DIR__ . '/qqzeng-ip-utf8.dat';
	$reader = new IpSearch($ipFile);

    /**
     * 此ip库只有国内信息，无法查到的或国外信息采用纯真ip库查询
     */
    if (!$tmp = $reader->get($ip)) {
        return get_location_ip2($ip) ?: false;
    }

    $tmp2 = array_slice(explode('|', $tmp), 0, 6);

    if ($tmp2[0] == '亚洲' && $tmp2[1] == '中国') {
        $tmp2 = array_slice($tmp2, 2, 4);
    }

    return implode('', $tmp2);
}


/**
 * getClientIp
 * 获取客户端IP地址
 *
 * @return void
 */
function getClientIp() {
    $ip = '';

    if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown',$arr);

        if(false !== $pos) {
            unset($arr[$pos]);
        }

        $ip = trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return $ip;
}

/**
 * getSiterName
 * 返回站长名称
 *
 * @param mixed $uid
 * @return void
 */
function getSiterName($uid) {
    $m = D2('Siter');

    if(!$r = $m->getByUid($uid)) {
        return '未知';
    }

    return $r['user_name'];
}

/**
 * getSiteStatusCn
 * 返回网站状态中文名称
 *
 * @param mixed $s
 * @return void
 */
function getSiteStatusCn($s) {
    $cn = C('SITE_STATUS');
    $s  = (int)$s;

    return array_key_exists($s, $cn) ? $cn[$s] : '未知';
}

/**
 * getBankNameCn
 * 返回银行中文名称
 *
 * @param mixed $n
 * @return void
 */
function getBankNameCn($name) {
    $cn   = C('BANK');
    $name = strtoupper($name);

    return array_key_exists($name, $cn) ? $cn[$name] : '未知';
}

/**
 * getPayLogStatusCn
 * 返回支付日志状态的中文名称
 *
 * @param mixed $s
 * @return void
 */
function getPayLogStatusCn($s) {
    $cn = C('PAY_LOG_STATUS');
    $s  = (int)$s;

    return array_key_exists($s, $cn) ? $cn[$s] : '未知';
}


/**
 * getMoneyStatusCn
 * 返回充值状态中文名称
 *
 * @param mixed $s
 * @return void
 */
function getMoneyStatusCn($s) {
    $cn = C('MONEY_STATUS');
    $s  = (int)$s;

    return array_key_exists($s, $cn) ? $cn[$s] : '未知';
}

/**
 * getUserTypeCn
 * 返回会员类型
 *
 * @param mixed $t
 * @return void
 */
function getUserTypeCn($t) {
    $cn = C('USER_TYPE');
    $t  = (int)$t;

    return array_key_exists($t, $cn) ? $cn[$t] : '未知';
}

/**
 * getLoginLogStatusCn
 * 返回登陆日志中登陆状态中文名称
 *
 * @param mixed $s
 * @return void
 */
function getLoginLogStatusCn($s) {
    $cn = C('LOGIN_LOG_STATUS');
    $s  = (int)$s;

    return array_key_exists($s, $cn) ? $cn[$s] : '未知';
}

/**
 * mSubstr
 * 截取字符串，超出长度部分显示省略号
 */
function mSubstr($str, $start=0, $length, $charset='utf-8', $suffix=true) {
    if(strlen($str) <= $length) {
        return $str;
    }

    $r = \Org\Util\String2::msubstr($str, $start, $length, $charset, $suffix);

    return $r;
}

/**
 * getMessageViewStatusCn
 * 返回短消息阅读状态中文名称
 *
 * @param mixed $s
 * @return void
 */
function getMessageViewStatusCn($s) {
    $cn = C('MESSAGE_VIEW_STATUS');
    $s  = (int)$s;

    return array_key_exists($s, $cn) ? $cn[$s] : '未知';
}

/**
 * getNewsTopStatusCn
 * 返回公告置顶状态中文名称
 *
 * @param mixed $s
 * @return void
 */
function getNewsTopStatusCn($s) {
}

/**
 * getNewsTopTag
 * 返回公告置标识
 *
 * @param mixed $s
 * @access public
 * @return void
 */
function getNewsTopTag($s) {
    $s = (int)$s;

    return $s === 1 ? '<span class="news-top-tag">[顶]</span>' : '';
}

/**
 * getNewsList
 * 返回文章列表
 *
 * @param mixed $cateId
 * @param int $limit
 * @return void
 */
function getNewsList($cateId = 0, $limit = 5) {
    $cateId = (int)$cateId;

    if($cateId < 0) {
        return false;
    }

    $limit = (int)$limit;
    $limit = $limit < 1 ? 5 : $limit;
    $m     = D2('News');
    $expr  = array('cate_id' => $cateId);

    if(!$r = $m->where($expr)->order('n_is_top DESC, n_id DESC')->limit($limit)->select()) {
        return false;
    }

    return $r;
}

/**
 * getZoneAutoViewCn
 * 返回广告位展示方式中文名称
 *
 * @param mixed $s
 * @return void
 */
function getZoneAutoViewCn($s) {
    $s = (int)$s;

    return $s ? '智能展示' : '自选';
}

/**
 * getZoneNameById
 * 返回广告位名称
 *
 * @param mixed $id
 * @return void
 */
function getZoneNameById($id) {
    $id = (int)$id;

    if(empty($id)) {
        return false;
    }

    if(!$r = D2('Zone')->field('zone_name')->getByZoneId($id)) {
        return false;
    }

    return $r['zone_name'];
}

/**
 * getDateCn
 * 返回当前日期的中文表示
 *
 * @return void
 */
function getDateCn() {
    $weekCn = array(
        0 => '日',
        1 => '一',
        2 => '二',
        3 => '三',
        4 => '四',
        5 => '五',
        6 => '六',
    );

    return date('Y年m月d日') . '&nbsp;&nbsp;星期' . $weekCn[date('w')];
}

function getLoginStatusCn($s) {
    $cn = C('LOGIN_STATUS');
    $s  = (int)$s;

    return array_key_exists($s, $cn) ? $cn[$s] : '未知';
}

/**
 * isSiter
 * 根据会员类型判断是否属于站长
 *
 * @param mixed $type
 * @return void
 */
function isSiter($type) {
    $type = (int)$type;
    import('Public.Model.SiterModel');

    return $type == SiterModel::TYPE;
}

/**
 * isAder
 * 根据会员类型判断是否属于广告主
 *
 * @param mixed $type
 * @return void
 */
function isAder($type) {
    $type = (int)$type;
    import('Public.Model.AderModel');

    return $type == AderModel::TYPE;
}

/**
 * isSiterService
 * 根据会员类型判断是否属于站长客服
 *
 * @param mixed $type
 * @return void
 */
function isSiterService($type) {
    $type = (int)$type;
    import('Public.Model.SiterServiceModel');

    return $type == SiterServiceModel::TYPE;
}

/**
 * isAderService
 * 根据会员类型判断是否属于广告主客服
 *
 * @param mixed $type
 * @return void
 */
function isAderService($type) {
    $type = (int)$type;
    import('Public.Model.AderServiceModel');

    return $type == AderServiceModel::TYPE;
}

/**
 * isAdmin
 * 根据会员类型判断是否属于管理员
 *
 * @param mixed $type
 * @return void
 */
function isAdmin($type) {
    $type = (int)$type;
    import('Public.Model.AdminModel');

    return $type == AdminModel::TYPE;
}

/**
 * getNewsClassName
 * 返回公告分类名称
 *
 * @param mixed $class
 * @access public
 * @return void
 */
function getNewsClassName($class) {
    $conf  = C('NEWS_CLASS');
    $class = (int)$class;

    return array_key_exists($class, $conf) ? $conf[$class] : '未知';
}

/**
 * getSiterServiceList
 * 获取允许登陆的站长客服列表
 *
 * @return void
 */
function getSiterServiceList() {
    $m = D2('SiterService');

    return ($r = $m->getAllowList()) ? $r : false;
}

/**
 * getAllSiterServiceList
 * 获取所有站长客服列表，包含禁止登陆的站长客服
 *
 * @return void
 */
function getAllSiterServiceList() {
    $m = D('SiterService');

    return ($r = $m->order('id ASC')->select()) ? $r : false;
}

function getRechargeGatewayCn($t) {
    $cn = C('RECHARGE_GATEWAY');
    $t  = strtolower(trim($t));

    return array_key_exists($t, $cn) ? $cn[$t] : '未知';
}

function getRechargeTypeCn($s) {
    $s  = (int)$s;
    $cn = C('RECHARGE_TYPES_2');

    return $cn[$s] ? $cn[$s] : '';
}

function stripslashes2(&$a) {
    $a = stripslashes($a);
}
/**
 * getFullUrl
 * 返回完整的网址，主要是检测$sUrl前面是否有http://，如果没有则补齐
 *
 * @param mixed $sUrl
 * @return void
 */
function getFullUrl($sUrl) {
    $sHttp = strtolower(substr($sUrl, 0, 7));

    if($sHttp != 'http://') {
        $sUrl = 'http://' . $sUrl;
    }

    return $sUrl;
}

/**
 * cacheApi
 *
 * 发送更新数据请求给主服务器
 *
 * 出错时返回异常，成功时返回true
 *
 * @param mixed $type
 * @param mixed $id
 * @return void
 */
function cacheApi($file, $args) {
    $url  = 'http://127.0.0.1/ck/Api/cache/';
    $url .= $file . '.php';
    $tmp  = post($url, $args);
    $msg  = json_decode($tmp, true);

    if (!$msg['s']) {
        throw new \Exception($msg['m']);
    }

    return true;
}


/**
 * getSiterTotalMoney
 * 获取当前登陆站长的未结算收入合计
 *
 * @return void
 */
function getSiterTotalMoney() {
    $uid = C('RUN_LOGIN_USER.id');

    if(!$user = D2('Siter')->getByUid($uid)) {
        return false;
    }

    $moneyScale = C('MONEY_SCALE');
    $money      = bcadd($user['money_1'], $user['money_2'], $moneyScale);
    $money      = bcadd($money, $user['money_3'], $moneyScale);

    return $money;
}

/**
 * getSiterTodayMoney
 * 获取当前登陆站长当天收入
 *
 * @return void
 */
function getSiterTodayMoney() {
    $uid = C('RUN_LOGIN_USER.id');
    $expr = array(
        'day' => date('Y-m-d'),
        'uid' => $uid,
    );

    if(!$money = D2('VSiterStats')->where($expr)->getField('siter_income')) {
        return 0;
    }

    return $money;
}

/**
 * getSiterZoneTotal
 * 获取当前登陆站长广告位数量
 *
 * @return void
 */
function getSiterZoneTotal() {
    $uid = C('RUN_LOGIN_USER.id');

    if(!$r = D2('Zone')->where(array('uid' => $uid))->count('*')) {
        return 0;
    }

    return $r;
}

/**
 * getSiterSiteTotal
 * 获取当前登陆站长网站数量
 *
 * @return void
 */
function getSiterSiteTotal() {
    $uid = C('RUN_LOGIN_USER.id');
    $expr = array('uid' => $uid);

    return ($r = D2('Site')->where($expr)->count('*')) ? $r : 0;
}

/**
 * getServicerQq
 * 返回客服QQ号
 *
 * @param mixed $uid
 * @return void
 */
function getServicerQq($uid) {
    $uid  = (int)$uid;
    $expr = array('uid' => $uid);
    $m    = D2('User');

    return ($r = $m->where($expr)->getField('qq')) ? $r : false;
}

/**
 * getAderMoney
 * 获取当前登陆广告主余额
 *
 * @return void
 */
function getAderMoney() {
    $uid  = C('RUN_LOGIN_USER.id');
    $m    = D2('User');
    $expr = array('uid' => $uid);

    return ($r = $m->where($expr)->getField('money_1')) ? $r : false;
}

/**
 * getAderPlanTotal
 * 获取当前登陆广告主计划总数
 *
 * @return void
 */
function getAderPlanTotal() {
    $uid  = C('RUN_LOGIN_USER.id');
    $m    = D2('Plan');
    $expr = array('uid' => $uid);

    return ($r = $m->where($expr)->count('*')) ? $r : false;
}

/**
 * getAderAdTotal
 * 获取当前登陆广告主广告素材总数
 *
 * @return void
 */
function getAderAdTotal() {
    $uid  = C('RUN_LOGIN_USER.id');
    $m    = D2('Ad');
    $expr = array('uid' => $uid);

    return ($r = $m->where($expr)->count('*')) ? $r : false;
}

/**
 * getAderTodayCost
 * 获取当前登陆广告主今天支出金额
 *
 * @return void
 */
function getAderTodayCost() {
    $uid  = C('RUN_LOGIN_USER.id');
    $m    = D2('PlanStats');
    $expr = array('uid' => $uid, 'day' => date('Y-m-d'));

    return ($r = $m->where($expr)->sum('ader_pay')) ? $r : false;
}

/**
 * getAderYesterdayCost
 * 获取当前登陆广告主昨天支出金额
 *
 * @return void
 */
function getAderYesterdayCost() {
    $uid  = C('RUN_LOGIN_USER.id');
    $m    = D2('PlanStats');
    $expr = array('uid' => $uid, 'day' => date('Y-m-d', strtotime('-1 day')));

    return ($r = $m->where($expr)->sum('ader_pay')) ? $r : false;
}

/**
 * getCostServerStatusCn
 * 返回从属计费服务器运行状态
 *
 * @param mixed $s
 * @return void
 */
function getCostServerStatusCn($s) {
    $s  = (int)$s;
    $cn = C('COST_SERVER_STATUS');

    return array_key_exists($s, $cn) ? $cn[$s] : '未知';
}

/**
 * filterDomain
 * 过滤网址中多余字符，只返回主机名
 *
 * @param mixed $url
 * @return void
 */
function filterDomain($url) {
    /**
     * 去掉http://
     */
    $tmp = str_replace('http://', '', $url);

    return array_shift(explode('/', $tmp));
}

/**
 * getRedirectUrl
 * 跳转代理函数
 *
 * @param mixed $url
 * @return void
 */
function getRedirectUrl($url) {
    $proxyApi = getFullUrl(C('REDIRECT_APP'));

    return $proxyApi . '?url=' . urlencode($url);
}

/**
 * getWaitAuditSiterCount
 * 获取待审核站长数量
 *
 * @return void
 */
function getWaitAuditSiterCount() {
    $m = D2('Siter');
    $expr = array('status' => 0, 'type' => 1);

    if(C('RUN_LOGIN_USER.type') == 3) {
        $expr['service_id'] = C('RUN_LOGIN_USER.service_id');
    }

    $r = $m->where($expr)->count();

    return empty($r) ? 0 : $r;
}

/**
 * getWaitAuditAderCount
 * 获取待审核广告主数量
 *
 * @return void
 */
function getWaitAuditAderCount() {
    $m    = D2('Ader');
    $expr = array('status' => 0, 'type' => 2);
    $r    = $m->where($expr)->count();

    return empty($r) ? 0 : $r;
}

/**
 * getWaitAuditSiteCount
 * 获取待审核网站数量
 *
 * @return void
 */
function getWaitAuditSiteCount() {
    $expr = array();

    if(C('RUN_LOGIN_USER.type') == 3) {
        $expr['service_id'] = C('RUN_LOGIN_USER.service_id');
    }

    $siteDomainTable = D2('SiteDomain')->getTableName();
    $join            = " RIGHT JOIN (SELECT DISTINCT site_id AS sid2 FROM {$siteDomainTable} where s_d_status=0) AS sd ON (site_id = sid2)";

    $m = D2('VSite');
    $r = $m->where($expr)->join($join)->count();

    return empty($r) ? 0 : $r;
}

/**
 * getDeductionStatusCn
 * 获取扣点状态中文名称
 *
 * @param mixed $s
 * @return void
 */
function getDeductionStatusCn($s) {
    $s = (int)$s;
    $cn = C('DEDUCTION_STATUS');

    return array_key_exists($s, $cn) ? $cn[$s] : '未知';
}

/**
 * getNewUserCn
 * 返回流量中属于新用户的标记
 *
 * @param mixed $s
 * @return void
 */
function getNewUserCn($s) {
    $s = (int)$s;

    return $s == 1 ? '[新]' : '';
}

/**
 * getClick2Detail
 * 返回二次点击详情
 *
 */
function getClick2Detail($day, $uid, $zoneId, $siteId, $adId, $ip) {
    $expr = array(
        'day'     => $day,
        'uid'     => $uid,
        'zone_id' => $zoneId,
        'site_id' => $siteId,
        'ad_id'   => $adId,
        'ip'      => $ip,
    );

    return D2('Click2Detail')->where($expr)->find();
}

/**
 * timeSub
 * 时间相减
 *
 * 时间格式必须是年月日时分秒的格式
 */
function timeSub($a, $b) {
    if(!$a = strtotime($a)) {
        return false;
    }

    if(!$b = strtotime($b)) {
        return false;
    }

    return $a - $b;
}

/**
 * showClickedObj
 * 显示被点击对象
 *
 * @param mixed $obj
 * @return void
 */
function showClickedObj($obj) {
    $obj = trim($obj);

    return (substr($obj, 0, 7) == 'http://') 
           ? '<a href="' . $obj . '" target="_blank">' . $obj . '</a>'
           : $obj;
}

/**
 * getLimitAdDomainCn
 * 获取投放域名限制状态中文信息
 *
 * @param mixed $s
 * @return void
 */
function getLimitAdDomainCn($s) {
    $s = (int)$s;

    return $s ? '限制' : '不限';
}

/**
 * getXiaXian
 * 获取指定$uid所属下线
 *
 * @param mixed $uid 如果未指定$uid，则直接选用当前登陆站长$uid
 * @return void
 */
function getXiaXian($uid = null) {
    $uid = empty($uid) ? C('RUN_LOGIN_USER.id') : $uid;

    if(empty($uid)) {
        return false;
    }

    $expr = array(
        'recommend' => $uid,
        'status'    => 2,
    );

    return D2('Siter')->where($expr)->order('uid DESC')->select();
}

/**
 * syslog2
 * 将错误信息发送给操作系统的syslogd
 *
 * @param mixed $log
 * @return void
 */
function syslog2($log) {
    openlog('newad', LOG_PID, LOG_USER);
    syslog(LOG_NOTICE, $log);
    closelog();
}

/**
 * getServerStatusCn
 * 返回服务器状态中文名称
 *
 * @param int $s
 * @return void
 */
function getServerStatusCn($s = 0) {
    $s = (int)$s;

    return $s ? '运行' : '停止';
}

/**
 * checkTableIsExists
 * 检测pg数据库中表或视图是否存在
 *
 * @param mixed $table
 * @param mixed $schema
 * @param string $type
 * @return void
 * 返回值false表示不存在，true表示存在
 */
function checkTableIsExists($table, $schema = null, $type = null) {
    $table  = trim($table);
    $schema = empty($schema)    ? null : strtolower(trim($schema));
    $type   = strtotime($type);
    $dbName = C('DB_NAME');
    $typeConf = array(
        'table' => 'BASE TABLE',
        'view'  => 'VIEW',
    );
    $typeVal = '';

    if(!empty($type)) {
        if(!in_array($type, $typeConf)) {
            return false;
        }

        $typeVal = $typeConf[$type];
    }

    $expr = "table_name='{$table}'";

    if(!empty($schema)) {
        $expr .= " AND table_schema='{$schema}' ";
    }

    if(!empty($typeVal)) {
        $expr .= " AND table_type='{$typeVal}' ";
    }

    $sql = "SELECT COUNT(*) as total FROM information_schema.tables WHERE {$expr} LIMIT 1";

    if(!$r = M()->query($sql)) {
        return false;
    }

    return empty($r[0]['total']) ? false : true;
}  

/**
 * getSiterServiceIncome
 * 返回站长客服提成
 *
 * @param mixed $uid
 * @return void
 */
function getSiterServiceIncome($uid) {
    $uid = (int)$uid;
    $expr = array(
        'uid'  => $uid,
        'type' => 3,
    );

    $r = M('Usr')->field('money_1 AS money')->where($expr)->find();

    return $r ? $r['money'] : null;
}

/**
 * checkAderPlanPriv
 * 检测当前广告主是否有控制计划的相应权限
 *
 * @param mixed $priv 指定需要检测的权限
 * @return void
 */
function checkAderPlanPriv($priv) {
    $ader  = C('RUN_LOGIN_USER');
    $privs = explode(',', $ader['accountname']);

    return in_array($priv, $privs);
}

/**
 * getPlanDeviceNameById
 * 返回投放终端名称
 *
 * @param mixed $deviceId
 * @return void
 */
function getPlanDeviceNameById($deviceId) {
    $devices  = getPlanDevices();
    $deviceId = (int)$deviceId;

    return empty($devices[$deviceId]) ? '' : $devices[$deviceId];
}

/**
 * getDevices
 * 返回设备信息
 *
 * @access public
 * @return void
 */
function getDevices() {
    return D('Device')->getDevices();
}

/**
 * getDeviceName
 * 根据设备编号返回设备名称
 *
 * @param mixed $device
 * @return void
 */
function getDeviceName($device) {
    $devices = C('PLAN_DEVICES');
    return empty($devices[$device]) ? '未知' : $devices[$device];
}

/**
 * getAdTodayCtr
 * 返回指定广告当日的点击率
 *
 * @param mixed $adId
 * @access public
 * @return void
 */
function getAdTodayCtr($adId) {
    $m    = M('stats.v_ad_stats');
    $expr = [
        'day'   => date('Y-m-d'),
        'ad_id' => $adId,
    ];

    if (!$r = $m->where($expr)->find()) {
        return 0;
    }

    return getCtr($r['view'], $r['num'] + $r['deduction']);
}

/**
 * checkPlanType
 * 验证计划类型是否正确
 * 正确返回true，错误返回false
 *
 * @param mixed $type
 * @access public
 * @return void
 */
function checkPlanType($type) {
    $type  = strtolower($type);
    $types = C('PLAN_TYPE');

    return array_key_exists($type, $types);
}

/**
 * checkDeviceId
 * 验证设备编号是否正确
 * 成功返回true，出错返回false
 *
 * @param mixed $id
 * @access public
 * @return void
 */
function checkDeviceId($id) {
    return D('Device')->checkById($id);
}

function isCostServerCn($s) {
    $s = (int)$s;

    return $s ? '是' : '否';
}

/**
 * getApi
 *
 * @param mixed $url
 * @return void
 */
function getApi($sUrl) {
    $rCh = curl_init($sUrl);
    curl_setopt($rCh, CURLOPT_RETURNTRANSFER, 1);   //不直接输出获取的数据
    curl_setopt($rCh, CURLOPT_CONNECTTIMEOUT, 3);   //连接超时，3秒如果连接不成功，则超时
    curl_setopt($rCh, CURLOPT_CONNECTTIMEOUT_MS, 3000); //尝试重连超时时间，单位毫秒
    curl_setopt($rCh, CURLOPT_TIMEOUT, 4); // 执行超时(秒)，一定要加上此项，否则有时可能因$sUrl访问不成功导致进程阻塞
    curl_setopt($rCh, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:28.0) Gecko/20100101 Firefox/28.0');

    for($i=0; $i<10; $i++) {
        $sR      = curl_exec($rCh);
        $errorId = curl_errno($rCh);

        if($errorId) {
            echo 'Curl error:' . "{$sUrl} error id={$errorId}\t" . curl_error($rCh) . PHP_EOL;
            //syslog2("curl {$sUrl} " . curl_error($rCh));
        }

        /**
         * errorId = 28　　28表示连接超时
         */
        if($errorId != 28) {
            break;
        }
    }

    curl_close($rCh);

    return $sR;
}


/**
 * getWaitCollectClickListIndex
 * 返回待采集计费队列索引
 *
 * @param mixed $ip
 * @access public
 * @return void
 */
function getWaitCollectClickListIndex($ip) {
    $api = '/ck/a.php?c=ClickListIndex&a=getIndex';
    $url = getFullUrl($ip . $api);
    $r   = getApi($url);

    if (!$msg = json_decode($r, true)) {
        return '';
    }

    if (!$msg['s']) {
        return $msg['m'];
    }

    $html = '<ul class="list-abc">';

    foreach ($msg['d'] as $k => $v) {
        $_date = date('Y-m-d H:i:s', $v['timestamp']);
        $html .= "<li><b>{$_date}</b><i>{$v['timestamp']}</i><u>{$v['len']}</u></li>";
    }

    $html .= '</ul>';

    return $html;
}


/**
 * getWaitCollectP2SetIndex
 * 返回待采集P2索引
 *
 * @param mixed $ip
 * @access public
 * @return void
 */
function getWaitCollectP2SetIndex($ip) {
    $api = '/ck/a.php?c=P2SetIndex&a=getIndex';
    $url = getFullUrl($ip . $api);
    $r   = getApi($url);

    if (!$msg = json_decode($r, true)) {
        return '';
    }

    if (!$msg['s']) {
        return $msg['m'];
    }

    $html = '<ul class="list-abc">';

    foreach ($msg['d'] as $k => $v) {
        $_date = date('Y-m-d H:i:s', $v['timestamp']);
        $html .= "<li><b>{$_date}</b><i>{$v['timestamp']}</i><u>{$v['len']}</u></li>";
    }

    $html .= '</ul>';

    return $html;
}

/**
 * isExistsMaster
 * 是否存在主服务器
 *
 * @access public
 * @return void
 */
function isExistsMaster() {
    return D('Server')->isExistsMaster();
}

/**
 * parsePgArray
 * 分解PostgreSQL数组为PHP数组
 *
 * @param mixed $val
 * @access public
 * @return void
 */
function parsePgArray($val) {
    return explode(',', trim($val, '{}'));
}

/**
 * buildPgArray
 * 将PHP数组转成PostgreSQL数组
 * 此函数只适用于数值型数组
 *
 * @param mixed $vals
 * @access public
 * @return void
 */
function buildPgArray($vals) {
    return '{' . implode(',', $vals) . '}';
}

/**
 * getServerTypeCn
 * 返回服务器类型中文名称
 *
 * @param mixed $type
 * @access public
 * @return void
 */
function getServerTypeCn($type) {
    $types = parsePgArray($type);
    $conf  = C('SERVER_TYPE');
    $r     = [];

    foreach ($types as $k => $v) {
        if (!empty($conf[$v])) {
            $r[] = $conf[$v];
        }
    }

    return $r;
}

/**
 * getFirendCacpcity
 * 返回友好的容量值
 *
 * @param mixed $val
 * @access public
 * @return void
 */
function getFirendCacpcity($val) {
    $units = ['KB', 'MB', 'GB', 'TB', 'PB'];
    $step  = 1024;

    foreach ($units as $v) {
        $val = $val / $step;

        if ($val < $step) {
            $val = ceil($val);
            break;
        }
    }

    return $val . $v;
}

/**
 * getUserName
 * 返回会员名称
 *
 * @param mixed $id
 * @access public
 * @return void
 */
function getUserName($id) {
    $r = '';

    if ($record = D('User')->where(['id' => $id])->find()) {
        $r = $record['name'];
    }

    return $r;
}

/**
 * getRelationAdTypes
 * 返回广告计划关联的可用广告类型
 *
 * @param mixed $planType
 * @access public
 * @return void
 */
function getRelationAdTypes($planType) {
    $planType        = strtolower($planType);
    $relationAdTypes = C('PLAN_TYPE_RELATION_AD_TYPE');

    return $relationAdTypes[$planType] ? $relationAdTypes[$planType] : [];
}


/**
 * alert
 * 以js的方式弹出信息并回退到上一步
 *
 * @param mixed $m
 * @access public
 * @return void
 */
function alert($m) {
    $html = <<<EOD
<meta http-equiv='Content-Type'' content='text/html; charset=utf-8'>
<script>alert('{$m}');history.go(-1);</script>
EOD;

    exit($html);
}

/**
 * post
 * 以post方式提交数据至$url
 *
 * todo:加入curl错误信息处理
 *
 * @param mixed $url
 * @param mixed $args
 * @param int $timeout
 * @access public
 * @return void
 */
function post($url, $args, $timeout = 5) {
	return true;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   //不直接输出获取的数据
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($args));
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

/**
 * intvals
 * 将单值或一维数组中所有值转换成数值型
 * 值为0的会被过滤掉
 *
 * @param mixed $a
 * @access public
 * @return void
 */
function intvals($a) {
    if (!is_array($a)) {
        return (int)$a;
    }

    return array_filter($a, function($v) {
        return (int)$v;
    });
}

/**
 * getShareDomain
 * 返回分享到朋友圈时使用的域名
 *
 * @access public
 * @return void
 */
function getShareDomain() {
    $file = __DIR__ . '/../../../a.domain';

    return ($r = file_get_contents($file))
           ? trim($r)
           : '';
}

/**
 * get_net_type_cn
 * 返回联网方式中文名称
 *
 * @param mixed $s
 * @access public
 * @return void
 */
function get_net_type_cn($s) {
    $s  = (int)$s;
    $cn = C('NETTYPES');

    return $cn[$s] ?? '未知';
}

/**
 * get_os_type_cn
 * 返加手机系统类型中文名称
 *
 * @param mixed $s
 * @access public
 * @return void
 */
function get_os_type_cn($s) {
    $s  = (int)$s;
    $cn = C('OS_TYPES');

    return $cn[$s] ?? '未知';
}

function get_isp_type_cn($s) {
    $s  = (int)$s;
    $cn = C('ISP_TYPES');

    return $cn[$s] ?? '未知';
}
function yesterday($record){
	//$day = date('Ymd');
	$day = '2017-01-07';
	$yesterday=0;
	foreach($record as $v){
		if($v['day'] == $day){
			$yesterday += $v['ader_pay'];
		}
	}
	return $yesterday;
}
function today($record){
	//$day = date('Ymd');
	$day = '2017-01-08';
	$today=0;
	foreach($record as $v){
		if($v['day'] == $day){
			$today += $v['ader_pay'];
		}
	}
	return $today;
}
function money($record){
	
}
